﻿/*
 *  Source code courtesy of the desktopWeb.CodePlex.com community project. See MS-PL license on Codeplex.com. 
 *  This is beta code not intended for a production application.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Activities;
using System.Net;
using System.Data.SqlClient;
using System.ComponentModel;

namespace MyData.Activities.SQLAzure
{
  [Designer(typeof(MyData.Activities.Designers.ConnectionActivityDesigner))]
  public sealed class ConnectionBuilderActivity : CodeActivity
  {
    //The LoginActivity can supply the NetworkCredentials
    [RequiredArgument]
    public InArgument<ICredentials> NetworkCredential { get; set; }

    //Server name such as {your server name}.database.windows.net
    [RequiredArgument]
    public InArgument<String> DataSource { get; set; }

    //Database name such as "AdventureWorks"
    [RequiredArgument]
    public InArgument<String> InitialCatalog { get; set; }

    public OutArgument<SqlConnectionStringBuilder> SqlConnectionBuilder { get; set; }

    protected override void Execute(CodeActivityContext context)
    {
      NetworkCredential credentials = (NetworkCredential)this.NetworkCredential.Get(context);
      string dataSource = DataSource.Get(context);
      string initialCatalog = InitialCatalog.Get(context);

      if (credentials != null)
      {
        SqlConnectionStringBuilder connStringBuilder = new SqlConnectionStringBuilder();
        connStringBuilder.DataSource = dataSource;
        connStringBuilder.InitialCatalog = initialCatalog;

        //Next: Make IntegratedSecurity test more definitive
        if (credentials.Password == string.Empty)
        {
          connStringBuilder.IntegratedSecurity = true;
        }
        else
        {
          //SQLAzure
          connStringBuilder.Encrypt = true;
          connStringBuilder.TrustServerCertificate = false;

          //Gets UserId and Password from LoginActivity.Credentials
          connStringBuilder.UserID = credentials.UserName;
          connStringBuilder.Password = credentials.Password;
        }
        SqlConnectionBuilder.Set(context, connStringBuilder);
      }
    }
  }
}
